package com.sunlong.jiangwei.service.impl;

import com.sunlong.jiangwei.dao.JwStoreMapper;
import com.sunlong.jiangwei.entity.JwStore;
import com.sunlong.jiangwei.service.IJwStoreService;
import com.sunlong.jiangwei.util.ErrorMapUtils;
import com.sunlong.jiangwei.util.MinioUtils;
import com.sunlong.jiangwei.vo.JwStoreVo;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 孙龙
 * @since 2021-02-19
 */
@Service
public class JwStoreServiceImpl implements IJwStoreService {

    @Autowired
    private JwStoreMapper jwStoreMapper;

    @Autowired
    private MinioUtils minioUtils;

    /**
     * 查询所有店铺
     *
     * @return
     */
    @Override
    public List<JwStoreVo> findAll() {
        List<JwStore> jwStoreList = jwStoreMapper.selectAll();
        List<JwStoreVo> jwStoreVos = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY年MM月dd日 HH:mm:ss");
        for (JwStore jwStore : jwStoreList) {
            JwStoreVo jwStoreVo = new JwStoreVo();
            jwStoreVo.setStoreId(Long.toString(jwStore.getStoreId()));
            jwStoreVo.setStoreName(jwStore.getStoreName());
            jwStoreVo.setStoreImage(jwStore.getStoreImage());
            jwStoreVo.setStoreStartTime(sdf.format(jwStore.getStoreStartTime()));
            jwStoreVos.add(jwStoreVo);
        }
        return jwStoreVos;
    }

    /**
     * 新增店铺
     *
     * @param context
     * @return
     */
    @Override
    @Transactional
    public Map<String, String> add(Map<String, Object> context) {
        String storeName = (String) context.get("storeName");
        Map<String, String> map = new HashMap<>();
        // 查询判断店铺不能重名
        if (!StringUtils.isEmpty(storeName)) {
            JwStore jwStore1 = new JwStore();
            jwStore1.setStoreName(storeName);
            List<JwStore> select = jwStoreMapper.select(jwStore1);
            if (select.size() > 0) {
                return ErrorMapUtils.putErrorMap(map, "已存在同名店铺！");
            }
            jwStore1.setStoreStartTime(new Date());
            jwStoreMapper.insert(jwStore1);
            // 上传图片到minio并且将返回路径插入数据库
            uploadAndUpdateImage(storeName, context);
        }
        return map;
    }

    /**
     * 上传图片到minio并且将返回路径插入数据库
     *
     * @param storeName
     * @param context
     */
    private void uploadAndUpdateImage(String storeName, Map<String, Object> context) {
        System.out.println(storeName);
        for (Map.Entry<String, Object> entry : context.entrySet()) {
            System.out.print(entry.getKey());
            System.out.println("," + entry.getValue());
        }
        // 获取id和name作为上传图片的key
        String modeStr = (String) context.get("mode");
        int mode = modeStr.equals(".png") ? 0 : 1;
        InputStream inputStream = (InputStream) context.get("inputStream");
        Example example = new Example(JwStore.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("storeName", storeName);
        JwStore jwStore = jwStoreMapper.selectOneByExample(example);
        // key的格式为 "id_name"
        String key = jwStore.getStoreId() + "_" + System.currentTimeMillis();
        try {
            //更新数据库图片地址
            String imageUrl = minioUtils.upload("store", mode, inputStream, key);
            jwStoreMapper.updateImageByStoreId(imageUrl, jwStore.getStoreId());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据id删除店铺
     *
     * @param context
     * @return
     */
    @Override
    public Map<String, String> delete(Map<String, Object> context) {
        Long id = Long.parseLong((String)context.get("id"));
        JwStore jwStore = jwStoreMapper.selectByPrimaryKey(id);
        Map<String, String> map = new HashMap<>();
        if (null == jwStore) {
            return ErrorMapUtils.putErrorMap(map, "所传参数id对应数据不存在");
        }
        try {
            String path = getPath(jwStore);
            minioUtils.deleteMinioFile("store", path);
        } catch (Exception e) {
            return ErrorMapUtils.putErrorMap(map, "minio删除文件出错");
        }
        jwStoreMapper.deleteByPrimaryKey(id);
        return map;
    }

    @NotNull
    private String getPath(JwStore jwStore) {
        String path = new StringBuilder()
                .append(Long.toString(jwStore.getStoreId()))
                .append("_").append(jwStore.getStoreName())
                .append(jwStore.getStoreImage().substring(jwStore.getStoreImage().lastIndexOf("."))).toString();
        return path;
    }


    /**
     * 修改店铺信息（名称，头像）
     *
     * @param context
     * @return
     */
    @Transactional
    @Override
    public Map<String, String> modify(Map<String, Object> context) {
        String name = (String) context.get("name");
        InputStream image = (InputStream) context.get("inputStream");
        Long id = Long.parseLong((String) context.get("id"));
        Map<String, String> map2 = new HashMap<>();
        if (!StringUtils.isEmpty(name)) {
            // 修改名称
            JwStore jwStore = new JwStore();
            jwStore.setStoreName(name);
            List<JwStore> select = jwStoreMapper.select(jwStore);
            if (select.size() > 0 && !Long.toString(id).equals(Long.toString(select.get(0).getStoreId()))) {
                return ErrorMapUtils.putErrorMap(map2, "已存在同名店铺！");
            }
        }
        if (null != image) {
            // 先删除本来存储的图片
            String path = getPath(jwStoreMapper.selectByPrimaryKey(id));
            try {
                minioUtils.deleteMinioFile("store", path);
            } catch (Exception e) {
                return ErrorMapUtils.putErrorMap(map2, "minio删除文件出错");
            }
        }
        if (!StringUtils.isEmpty(name)) {
            jwStoreMapper.updateNameById(name, id);
        }
        if (null != image) {
            Map<String, Object> map = new HashMap<>();
            // 将图片插入minio并将返回路径插入数据库中
            map.put("inputStream", image);
            map.put("mode", context.get("mode"));
            uploadAndUpdateImage(name, map);
        }
        return map2;
    }

    @Override
    public JwStore list(Map<String, Object> map) {
        Long storeId = ((Integer)map.get("storeId")).longValue();
        JwStore jwStore = new JwStore();
        jwStore.setStoreId(storeId);
        JwStore jwStore1 = jwStoreMapper.selectOne(jwStore);
        return jwStore1;
    }
}
